package com.zdkj.subway.st.controller;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zdkj.common.core.constant.CommonConstants;
import com.zdkj.common.core.constant.SecurityConstants;
import com.zdkj.common.core.util.R;
import com.zdkj.common.log.annotation.SysLog;
import com.zdkj.common.security.annotation.Inner;
import com.zdkj.common.security.util.SecurityUtils;
import com.zdkj.subway.st.constant.enums.TicketRecycleDeliveryEnum;
import com.zdkj.subway.st.dto.in.SwTkTemporaryDistributionPlanNoticeDTO;
import com.zdkj.subway.st.entity.SwTkTemporaryDistributionPlanNotice;
import com.zdkj.subway.st.fegin.SubwayStmService;
import com.zdkj.subway.st.service.SwTkTemporaryDistributionPlanNoticeService;
import com.zdkj.subway.st.service.SwTkTicketDeliveryService;
import com.zdkj.subway.st.util.LocalDateConverter;
import com.zdkj.subway.st.util.LocalDateTimeConverter;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;


/**
 * 线网临时配收计划通知
 *
 * @author cuilei
 * @date 2020-06-16 11:29:28
 */
@RestController
@AllArgsConstructor
@RequestMapping("/swtktemporarydistributionplannotice")
@Api(value = "swtktemporarydistributionplannotice", tags = "线网临时配收计划通知管理")
public class SwTkTemporaryDistributionPlanNoticeController {
    private final SwTkTemporaryDistributionPlanNoticeService swTkTemporaryDistributionPlanNoticeService;
    private final SwTkTicketDeliveryService swTkTicketDeliveryService;
    private final SubwayStmService subwayStmService;

    /**
     * 分页查询
     *
     * @param page                                分页对象
     * @param swTkTemporaryDistributionPlanNotice 线网临时配收计划通知
     * @return
     */
    @ApiOperation(value = "分页查询", notes = "分页查询")
    @GetMapping("/page")
    public R getSwTkTemporaryDistributionPlanNoticePage(Page page, SwTkTemporaryDistributionPlanNotice swTkTemporaryDistributionPlanNotice) {
        String dateCondition = swTkTemporaryDistributionPlanNotice.getDistributionTimeDTO();
        QueryWrapper<SwTkTemporaryDistributionPlanNotice> queryWrapper = Wrappers.query(swTkTemporaryDistributionPlanNotice);
        //LambdaQueryWrapper<SwTkTemporaryDistributionPlanNotice> queryWrapper = Wrappers.query(swTkTemporaryDistributionPlanNotice).lambda();
        queryWrapper.orderByDesc("distribution_time","confirm_time");
        queryWrapper.lambda().eq(SwTkTemporaryDistributionPlanNotice::getLineCode, SecurityUtils.getUser().getLineCode());
        queryWrapper.lambda().eq(SwTkTemporaryDistributionPlanNotice::getStationCode, SecurityUtils.getUser().getStationCode());
        if (StringUtils.isNotBlank(dateCondition)) {
            queryWrapper.lambda().likeRight(SwTkTemporaryDistributionPlanNotice::getDistributionTime, dateCondition);
        }
        return R.ok(swTkTemporaryDistributionPlanNoticeService.page(page, queryWrapper));
    }

    /**
     * 通过id查询线网临时配收计划通知
     *
     * @param id id
     * @return R
     */
    @ApiOperation(value = "通过id查询", notes = "通过id查询")
    @GetMapping("/{id}")
    public R getById(@PathVariable("id") Integer id) {
        return R.ok(swTkTemporaryDistributionPlanNoticeService.getById(id));
    }

    /**
     * 批量新增线网临时配收计划通知
     *
     * @param swTkTemporaryDistributionPlanNotices 线网临时配收计划通知
     * @return R
     */
    @ApiOperation(value = "批量新增线网临时配收计划通知", notes = "批量新增线网临时配收计划通知")
    @PostMapping
    @PreAuthorize("@pms.hasPermission('st_sw_tk_temporary_distribution_plan_notice_add')")
    @Inner
    public R save(@RequestBody List<SwTkTemporaryDistributionPlanNoticeDTO> swTkTemporaryDistributionPlanNotices) {
        return R.ok(swTkTemporaryDistributionPlanNoticeService.saveBathByNotice(swTkTemporaryDistributionPlanNotices));
    }

    /**
     * 批量新增线网临时配收计划通知
     *
     * @param swTkTemporaryDistributionPlanNotices 线网临时配收计划通知
     * @return R
     */
    @ApiOperation(value = "批量新增线网临时配收计划通知", notes = "批量新增线网临时配收计划通知")
    @PostMapping("/info")
    @Inner
    public R saveBath(@RequestBody List<SwTkTemporaryDistributionPlanNoticeDTO> swTkTemporaryDistributionPlanNotices) {
        return R.ok(swTkTemporaryDistributionPlanNoticeService.saveBathByNotice(swTkTemporaryDistributionPlanNotices));
    }

    /**
     * 线网配收计划通知确认
     *
     * @param listIds 通知的ID
     * @return
     */
    @ApiOperation(value = "线网配收计划通知确认", notes = "线网配收计划通知确认")
    @SysLog("线网配收计划通知确认")
    @PostMapping("/confirm")
    public R noticeConfirm(@RequestBody List<Integer> listIds) {
        List<SwTkTemporaryDistributionPlanNotice> confirmUpdateList = new ArrayList<>();
        List<Integer> deliveryList = new ArrayList<>();
        List<Integer> recoverList = new ArrayList<>();
        String personCode = SecurityUtils.getUser().getUserCode();
        String personName = SecurityUtils.getUser().getNikeName();
        listIds.forEach(item -> {
            //根据ID查到通知，并更新操作人,确认时间
            SwTkTemporaryDistributionPlanNotice confirmUpdateItem =
                    swTkTemporaryDistributionPlanNoticeService.getById(item);
            confirmUpdateItem.setNoticeConfirm(CommonConstants.CONFIRM);
            confirmUpdateItem.setOperatorPersonCode(personCode);
            confirmUpdateItem.setOperatorPersonName(personName);
            confirmUpdateItem.setConfirmTime(LocalDateTime.now());
            confirmUpdateList.add(confirmUpdateItem);

            //同步状态到配送或回收
            if (TicketRecycleDeliveryEnum.DELIVERY.getCode().equals(confirmUpdateItem.getDistributionType())) {
                deliveryList.add(confirmUpdateItem.getRefId());
            }

            if (TicketRecycleDeliveryEnum.RECYCLE.getCode().equals(confirmUpdateItem.getDistributionType())) {
                recoverList.add(confirmUpdateItem.getRefId());
            }
        });
        if (!deliveryList.isEmpty()) {
            //调用车票配送接口确认通知
            swTkTicketDeliveryService.noticeConfirm(deliveryList);
        }
        if (!recoverList.isEmpty()) {
            //确认通知
            subwayStmService.ticketRecoverNoticeConfirm(recoverList, SecurityConstants.FROM_IN);
        }
        return R.ok(swTkTemporaryDistributionPlanNoticeService.updateBatchById(confirmUpdateList));
    }

    /**
     * 修改线网临时配收计划通知
     *
     * @param swTkTemporaryDistributionPlanNotice 线网临时配收计划通知
     * @return R
     */
    @ApiOperation(value = "修改线网临时配收计划通知", notes = "修改线网临时配收计划通知")
    @SysLog("修改线网临时配收计划通知")
    @PutMapping
    @PreAuthorize("@pms.hasPermission('st_sw_tk_temporary_distribution_plan_notice_edit')")
    public R updateById(@RequestBody SwTkTemporaryDistributionPlanNotice swTkTemporaryDistributionPlanNotice) {
        return R.ok(swTkTemporaryDistributionPlanNoticeService.updateById(swTkTemporaryDistributionPlanNotice));
    }

    /**
     * 通过id删除线网临时配收计划通知
     *
     * @param id id
     * @return R
     */
    @ApiOperation(value = "通过id删除线网临时配收计划通知", notes = "通过id删除线网临时配收计划通知")
    @SysLog("通过id删除线网临时配收计划通知")
    @DeleteMapping("/{id}")
    @PreAuthorize("@pms.hasPermission('st_sw_tk_temporary_distribution_plan_notice_del')")
    public R removeById(@PathVariable Integer id) {
        return R.ok(swTkTemporaryDistributionPlanNoticeService.removeById(id));
    }

    /**
     * 导出线路临时配收计划通知信息
     *
     * @param swTkTemporaryDistributionPlanNotice
     * @param response
     * @throws IOException
     */
    @ApiOperation(value = "导出线路临时配收计划通知信息", notes = "导出线路临时配收计划通知信息")
    @GetMapping("/export")
    @SysLog("导出线路临时配收计划通知信息")
    @PreAuthorize("@pms.hasPermission('st_sw_tk_temporary_distribution_plan_notice_export')")
    public void exportExcel(SwTkTemporaryDistributionPlanNotice swTkTemporaryDistributionPlanNotice, HttpServletResponse response) throws IOException {
        List<SwTkTemporaryDistributionPlanNotice> swTkTemporaryDistributionPlanNoticeList = swTkTemporaryDistributionPlanNoticeService.list(Wrappers.query(swTkTemporaryDistributionPlanNotice));
        String fileName = URLEncoder.encode("线路临时配收计划通知", "UTF-8");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName + System.currentTimeMillis() + ".xlsx");
        EasyExcel.write(response.getOutputStream(), SwTkTemporaryDistributionPlanNotice.class).registerConverter(new LocalDateTimeConverter())
                .registerConverter(new LocalDateConverter()).sheet("线路临时配收计划通知").doWrite(swTkTemporaryDistributionPlanNoticeList);
    }

}
